package com.ts.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DecimalFormat;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ImportExcel {
	/**
	 * 通过filename获取完整的路径名数据
	 * 
	 * @param filename
	 * @return
	 * @throws IOException
	 */
	public static Workbook getWeebWork(String filename) throws IOException {
		Workbook workbook = null;
		if (null != filename) {
			String fileType = filename.substring(filename.lastIndexOf("."), filename.length());
			FileInputStream fileStream = new FileInputStream(new File(filename));
			if (".xls".equals(fileType.trim().toLowerCase())) {
				workbook = new HSSFWorkbook(fileStream);// 创建 Excel 2003 工作簿对象
			} else if (".xlsx".equals(fileType.trim().toLowerCase())) {
				workbook = new XSSFWorkbook(fileStream);// 创建 Excel 2007 工作簿对象
			}
		}
		return workbook;
	}

	// 获取单元格的值
	public static String getValue(Cell cell) {
		if (cell != null) {
			if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
				return String.valueOf(cell.getBooleanCellValue());
			} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
				DecimalFormat df=new DecimalFormat("0");
				//System.out.println(df.format(cell.getNumericCellValue())+"---------------");
				return df.format(cell.getNumericCellValue());
			} else {
				return String.valueOf(cell.getStringCellValue());
			}
		}
		return "";
	}
	// 获取单元格的值
	public static String getValueNew(Cell cell) {
		DecimalFormat df = new DecimalFormat("########");
		if (cell != null) {
			if (cell.getCellType() == 4) {
				return String.valueOf(cell.getBooleanCellValue());
			} else if (cell.getCellType() == 0) {
				return String.valueOf(df.format(cell.getNumericCellValue()));
			} else {
				return String.valueOf(cell.getStringCellValue());
			}
		}
		return "";
	}
}
